const util = require('./util.js');
const api = require('../config/api.js');
/**
 * 判断用户是否登录
 * */
function checkLogin() {
    return new Promise(function (resolve, reject) {
        if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')){
            util.checkSession().then(()=>{
                reject(false)
            }).catch(()=>{
                resolve(true)
            })
        }else{

            resolve(true)
        }
    })
}
/**
 * 调用微信登录
 * */
function loginByWeixin() {
    let code = null;
    return new Promise(function (resolve, reject) {
        return util.login().then((res) => {
            code = res.code;
            console.log(code)
            wx.setStorageSync('token', code);
            return util.getUserInfo();
        }).then((userInfo) => {
            //登录远程服务器
            util.request(api.AuthLoginByWeixin, { min_pro:api.Program_id, code: code, userInfo: userInfo }, 'POST').then(res => {
                if (res.code === 1) {
                    //存储用户信息
                    console.log(res)
                    wx.setStorageSync('gameInfo', res);
                    wx.setStorageSync('userInfo', userInfo.userInfo);
                    resolve(res);
                } else {
                    reject(res);
                }
            }).catch((err) => {
                reject(err);
            });
        }).catch((err) => {
            reject(err);
        })
    });
}
module.exports = {
    loginByWeixin,
    checkLogin,
};